package xutil

import (
	"sync"
)

// Map 字典
type Map struct {
	m map[interface{}]interface{}
	l sync.RWMutex
}

// Init 初始化
func CreateMap() *Map {
	mp := &Map{
		m: make(map[interface{}]interface{}),
	}
	return mp
}
func (mp *Map) Reset() {
	mp.m = make(map[interface{}]interface{})
}

// Set 添加
func (mp *Map) Set(key interface{}, value interface{}) {
	mp.l.Lock()
	defer mp.l.Unlock()

	mp.m[key] = value
}

// Get 获取
func (mp *Map) Get(key interface{}) interface{} {
	mp.l.RLock()
	defer mp.l.RUnlock()

	return mp.m[key]
}

// ContainsKey 包含指定Key
func (mp *Map) ContainsKey(key interface{}) bool {
	mp.l.RLock()
	defer mp.l.RUnlock()

	return mp.m[key] != nil
}

// Delete 删除
func (mp *Map) Delete(key interface{}) {
	mp.l.Lock()
	defer mp.l.Unlock()

	delete(mp.m, key)
}

// Walk 遍历执行函数
func (mp *Map) Walk(f func(interface{}, interface{})) {
	mp.l.RLock()
	defer mp.l.RUnlock()

	for k, v := range mp.m {
		f(k, v)
	}
}

// Count 数量
func (mp *Map) Count() int {
	mp.l.RLock()
	defer mp.l.RUnlock()

	return len(mp.m)
}
